其他
数据呈现丨R与Office珠联璧合:如何实现R制图便捷导入PPT?
The following article is from R语言 Author jamieDee
笔者邀请您,先思考:
如何使用ggplot2包生成可以公开的高质量图形?
library("tidyverse")
library("officer")
library("rvg")
time_use <- rio::import("clean_data.csv")
time_use <- time_use %>%
filter(population %in% c("Male", "Female")) %>%
filter(activities %in% c("Personal care", "Sleep", "Eating",
"Employment", "Household and family care")) %>%
group_by(day) %>%
nest()
我只保留了两类:“Male”和“Female”,以及5项活动。接着按照day分组并把其余的nested在data中。以下就是呈现的状况:
time_use
## # A tibble: 3 x 2
## day data
## <chr> <list>
## 1 Year 2014_Monday til Friday <tibble [10 × 4]>
## 2 Year 2014_Saturday <tibble [10 × 4]>
## 3 Year 2014_Sunday <tibble [10 × 4]>
正如展现的那样,'time_use'是一个有两列的tibble,第一列'day'包含了days,第二列'data'是一个类型列,并且列中的每个元素是自身的tibbles。让我们看看其中一个的内容:
time_use$data[1]
## [[1]]
## # A tibble: 10 x 4
## population activities time time_in_minutes
## <chr> <chr> <chr> <int>
## 1 Male Personal care 11:00 660
## 2 Male Sleep 08:24 504
## 3 Male Eating 01:46 106
## 4 Male Employment 08:11 491
## 5 Male Household and family care 01:59 119
## 6 Female Personal care 11:15 675
## 7 Female Sleep 08:27 507
## 8 Female Eating 01:48 108
## 9 Female Employment 06:54 414
## 10 Female Household and family care 03:49 229
现在可以使用以下的代码为每一天绘制图了:
my_plots <- time_use %>%
mutate(plots = map2(.y = day, .x = data, ~ggplot(data = .x) + theme_minimal() +
geom_col(aes(y = time_in_minutes, x = activities, fill = population),
position = "dodge") +
ggtitle(.y) +
ylab("Time in minutes") +
xlab("Activities")))
my_plots
## # A tibble: 3 x 3
## day data plots
## <chr> <list> <list>
## 1 Year 2014_Monday til Friday <tibble [10 × 4]> <S3: gg>
## 2 Year 2014_Saturday <tibble [10 × 4]> <S3: gg>
## 3 Year 2014_Sunday <tibble [10 × 4]> <S3: gg>
my_plots$plots[1]
## [[1]]
read_pptx() %>%
add_slide(layout = "Title and Content", master = "Office Theme") %>%
ph_with_vg(code = print(one_plot), type = "body") %>%
print(target = path)
左右滑动查看更多
我写了一个包装把一系列的参数结合起来:
create_pptx <- function(plot, path){
if(!file.exists(path)) {
out <- read_pptx()
} else {
out <- read_pptx(path)
}
out %>%
add_slide(layout = "Title and Content", master = "Office Theme") %>%
ph_with_vg(code = print(plot), type = "body") %>%
print(target = path)
}
map(my_plots$plots, create_pptx, path = "test.pptx")
## [[1]]
## [1] "/home/cbrunos/Documents/b-rodrigues.github.com/content/blog/test.pptx"
##
## [[2]]
## [1] "/home/cbrunos/Documents/b-rodrigues.github.com/content/blog/test.pptx"
##
## [[3]]
## [1] "/home/cbrunos/Documents/b-rodrigues.github.com/content/blog/test.pptx"
►一周热文
统计计量丨政策效应评估的四种主流方法(Policy evaluation)
数据Seminar
这里是大数据、分析技术与学术研究的三叉路口
作者:JamieDee出处:R语言推荐:简华(何年华)编辑:青酱
欢迎扫描👇二维码添加关注